<template>
  <div class="statistics">
    <SideNav />
    <div class="main-content">
      <!-- 顶部数据卡片 -->
      <div class="stat-cards">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-code"></i>
          </div>
          <div class="stat-info">
            <h3>解题总数</h3>
            <div class="stat-value">{{ userStats.solvedCount }}</div>
            <div class="stat-trend positive" v-if="userStats.weeklyIncrease > 0">
              <i class="fas fa-arrow-up"></i>
              <span>较上周 +{{ userStats.weeklyIncrease }}</span>
            </div>
            <div class="stat-trend" v-else>
              <span>本周暂无新增</span>
            </div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-check-circle"></i>
          </div>
          <div class="stat-info">
            <h3>正确率</h3>
            <div class="stat-value">{{ userStats.acceptRate }}%</div>
            <div class="stat-trend positive" v-if="userStats.acceptRateChange > 0">
              <i class="fas fa-arrow-up"></i>
              <span>较上周 +{{ userStats.acceptRateChange }}%</span>
            </div>
            <div class="stat-trend" v-else>
              <span>保持稳定</span>
            </div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-calendar-check"></i>
          </div>
          <div class="stat-info">
            <h3>连续提交</h3>
            <div class="stat-value">{{ userStats.currentStreak }}天</div>
            <div class="stat-trend">
              <span>最长 {{ userStats.maxStreak }}天</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 主要统计区域 -->
      <div class="stat-grid">
        <!-- 提交历史图表 -->
        <div class="stat-panel">
          <h2>提交历史</h2>
          <div class="chart-container">
            <v-chart class="chart" :option="submissionOption" autoresize />
          </div>
        </div>

        <!-- 题目难度分布 -->
        <div class="stat-panel">
          <h2>难度分布</h2>
          <div class="chart-container">
            <v-chart class="chart" :option="difficultyOption" autoresize />
          </div>
        </div>

        <!-- 最近提交 -->
        <div class="stat-panel">
          <h2>最近提交</h2>
          <div class="recent-submissions">
            <div v-for="submission in recentSubmissions" 
                 :key="submission.created_at" 
                 class="submission-item"
                 :class="submission.status.toLowerCase()">
              <div class="submission-info">
                <div class="problem-title">
                  {{ submission.title }}
                  <span class="difficulty-tag" :class="submission.difficulty.toLowerCase()">
                    {{ submission.difficulty }}
                  </span>
                </div>
                <div class="submission-time">{{ formatSubmissionTime(submission.created_at) }}</div>
              </div>
              <div class="submission-status">
                <i :class="getStatusIcon(submission.status)"></i>
                {{ submission.status }}
              </div>
            </div>
          </div>
        </div>

        <!-- 解题进度 -->
        <div class="stat-panel">
          <h2>解题进度</h2>
          <div class="chart-container">
            <v-chart class="chart" :option="progressOption" autoresize />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SideNav from '@/components/SideNav.vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { 
  PieChart,
  BarChart,
  LineChart,
  HeatmapChart 
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
  CalendarComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import axios from 'axios'
import { baseURL } from '@/utils/api'

use([
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  HeatmapChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
  CalendarComponent
])

export default {
  name: 'StatisticsView',
  components: {
    SideNav,
    VChart
  },
  data() {
    return {
      recentSubmissions: [],
      activityData: [],
      difficultyData: {
        solved: { easy: 0, medium: 0, hard: 0 },
        total: { easy: 0, medium: 0, hard: 0 }
      },
      userStats: {
        solvedCount: 0,
        totalSubmissions: 0,
        acceptRate: 0,
        weeklyIncrease: 0,
        acceptRateChange: 0,
        currentStreak: 0,
        maxStreak: 0
      },
      // 提交历史配置
      submissionOption: {
        tooltip: {
          position: 'top',
          formatter: function (p) {
            return `${p.data[0]}: ${p.data[1]} 次提交`
          }
        },
        visualMap: {
          min: 0,
          max: 10,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: 20,
          inRange: {
            color: ['#e8f4ff', '#3498db']
          }
        },
        calendar: {
          top: 40,
          left: 30,
          right: 30,
          cellSize: ['auto', 20],
          range: this.getLastNDays(180),
          itemStyle: {
            borderWidth: 0.5
          },
          yearLabel: { show: false }
        },
        series: [{
          type: 'heatmap',
          coordinateSystem: 'calendar',
          data: []
        }]
      },
      // 难度分布配置
      difficultyOption: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: ['简单', '中等', '困难']
        },
        series: [
          {
            name: '已解决',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: [0, 0, 0],
            itemStyle: {
              color: '#42b983'
            }
          },
          {
            name: '未解决',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: [0, 0, 0],
            itemStyle: {
              color: '#e8f4ff'
            }
          }
        ]
      },
      // 解题进度配置
      progressOption: {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [
          {
            name: '解题进度',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 0, name: '已解决', itemStyle: { color: '#42b983' } },
              { value: 0, name: '未开始', itemStyle: { color: '#909399' } }
            ]
          }
        ]
      },
      problemStats: null
    }
  },
  methods: {
    getStatusIcon(status) {
      const icons = {
        'Accepted': 'fas fa-check-circle',
        'Wrong Answer': 'fas fa-times-circle',
        'Time Limit Exceeded': 'fas fa-clock',
        'Runtime Error': 'fas fa-exclamation-circle',
        'Compilation Error': 'fas fa-times-circle'
      }
      return icons[status] || 'fas fa-question-circle'
    },
    formatSubmissionTime(dateTime) {
      const now = new Date();
      const submissionDate = new Date(dateTime);
      const diffInMinutes = Math.floor((now - submissionDate) / (1000 * 60));

      if (diffInMinutes < 1) return '刚刚';
      if (diffInMinutes < 60) return `${diffInMinutes}分钟前`;
      
      const diffInHours = Math.floor(diffInMinutes / 60);
      if (diffInHours < 24) return `${diffInHours}小时前`;
      
      const diffInDays = Math.floor(diffInHours / 24);
      if (diffInDays < 30) return `${diffInDays}天前`;
      
      return submissionDate.toLocaleDateString();
    },
    getLastNDays(n) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * (n - 1))
      return [start.toISOString().split('T')[0], end.toISOString().split('T')[0]]
    },
    // 获取提交历史数据
    async fetchUserActivityHistory() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          console.error('用户未登录');
          return;
        }

        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getUserActivityHistory/${userId}`
        });

        if (response.data.result === 'success') {
          // 将活动数据转换为ECharts需要的格式 [日期, 数量]
          this.activityData = response.data.activities.map(item => [
            item.date, 
            item.count
          ]);
          
          // 更新日历图表
          this.submissionOption.series[0].data = this.activityData;
          this.submissionOption.visualMap.max = Math.max(
            ...this.activityData.map(item => item[1]), 
            5  // 至少为5，避免没有数据时显示异常
          );
          
          // 计算连续提交天数
          this.calculateStreaks();
        } else {
          console.error('获取用户活动历史失败：', response.data.message);
        }
      } catch (error) {
        console.error('获取用户活动历史失败:', error);
      }
    },
    // 计算连续提交天数
    calculateStreaks() {
      if (!this.activityData || this.activityData.length === 0) {
        this.userStats.currentStreak = 0;
        this.userStats.maxStreak = 0;
        return;
      }
      
      // 将活动数据转换为日期和次数的映射
      const activityMap = new Map();
      this.activityData.forEach(([date, count]) => {
        activityMap.set(date, count);
      });
      
      // 按日期排序
      const dates = [...activityMap.keys()].sort();
      
      // 计算最大连续天数
      let maxStreak = 0;
      let currentStreak = 0;
      let previousDate = null;
      
      // 遍历排序后的日期
      for (const date of dates) {
        const count = activityMap.get(date);
        const currentDate = new Date(date);
        
        // 如果当天有提交记录
        if (count > 0) {
          // 第一次遍历或与前一天相连
          if (previousDate === null) {
            currentStreak = 1;
          } else {
            const diffDays = Math.round((currentDate - previousDate) / (1000 * 60 * 60 * 24));
            
            // 如果是连续的一天
            if (diffDays === 1) {
              currentStreak++;
            } else {
              // 重新开始计数
              currentStreak = 1;
            }
          }
          
          previousDate = currentDate;
          maxStreak = Math.max(maxStreak, currentStreak);
        }
      }
      
      // 检查当前是否还在连续提交中
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      
      const todayStr = today.toISOString().split('T')[0];
      const yesterdayStr = yesterday.toISOString().split('T')[0];
      
      // 如果今天有提交，则当前连续天数就是计算出的最后一段连续天数
      if (activityMap.has(todayStr) && activityMap.get(todayStr) > 0) {
        this.userStats.currentStreak = currentStreak;
      } 
      // 如果昨天有提交但今天没有，连续天数仍然计算
      else if (activityMap.has(yesterdayStr) && activityMap.get(yesterdayStr) > 0) {
        this.userStats.currentStreak = currentStreak;
      }
      // 否则当前连续天数为0
      else {
        this.userStats.currentStreak = 0;
      }
      
      this.userStats.maxStreak = maxStreak;
    },
    // 获取题目统计信息
    async fetchProblemStats() {
      try {
        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getProblemStats`
        });

        if (response.data.result === 'success') {
          // 获取总题目数
          const totalCount = response.data.totalCount;
          
          // 获取不同难度的题目数量
          const difficultyStats = response.data.difficultyStats || {
            'EASY': 0,
            'MEDIUM': 0,
            'HARD': 0
          };
          
          // 存储总题目数据
          const totalByDifficulty = {
            'EASY': difficultyStats['EASY'] || 0,
            'MEDIUM': difficultyStats['MEDIUM'] || 0,
            'HARD': difficultyStats['HARD'] || 0
          };
          
          // 保存结果，供其他方法使用
          this.problemStats = {
            totalCount,
            totalByDifficulty
          };
          
        } else {
          console.error('获取题目统计信息失败：', response.data.message);
          // 设置默认值
          this.problemStats = {
            totalCount: 0,
            totalByDifficulty: {
              'EASY': 0,
              'MEDIUM': 0,
              'HARD': 0
            }
          };
        }
      } catch (error) {
        console.error('获取题目统计信息失败:', error);
        // 设置默认值
        this.problemStats = {
          totalCount: 0,
          totalByDifficulty: {
            'EASY': 0,
            'MEDIUM': 0,
            'HARD': 0
          }
        };
      }
    },
    // 获取用户难度统计
    async fetchUserDifficultyStats() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          console.error('用户未登录');
          return;
        }

        // 确保题目统计信息已经获取
        if (!this.problemStats) {
          await this.fetchProblemStats();
        }

        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getUserDifficultyStats/${userId}`
        });

        if (response.data.result === 'success') {
          const stats = response.data.difficultyStats || [];
          
          // 初始化难度数据
          const solvedByDifficulty = {
            'EASY': 0,
            'MEDIUM': 0,
            'HARD': 0
          };
          
          // 更新已解决的题目数量
          stats.forEach(stat => {
            const difficulty = stat.difficulty;
            const count = parseInt(stat.count) || 0;
            
            if (solvedByDifficulty.hasOwnProperty(difficulty)) {
              solvedByDifficulty[difficulty] = count;
            }
          });
          
          // 使用从API获取的总题目数
          const totalByDifficulty = this.problemStats.totalByDifficulty;
          
          // 更新难度分布数据
          this.difficultyData = {
            solved: {
              easy: solvedByDifficulty['EASY'],
              medium: solvedByDifficulty['MEDIUM'],
              hard: solvedByDifficulty['HARD']
            },
            total: {
              easy: totalByDifficulty['EASY'],
              medium: totalByDifficulty['MEDIUM'],
              hard: totalByDifficulty['HARD']
            }
          };
          
          // 更新难度分布图表
          this.difficultyOption.series[0].data = [
            solvedByDifficulty['EASY'],
            solvedByDifficulty['MEDIUM'],
            solvedByDifficulty['HARD']
          ];
          
          this.difficultyOption.series[1].data = [
            totalByDifficulty['EASY'] - solvedByDifficulty['EASY'],
            totalByDifficulty['MEDIUM'] - solvedByDifficulty['MEDIUM'],
            totalByDifficulty['HARD'] - solvedByDifficulty['HARD']
          ];
          
          // 更新解题进度图表
          const totalSolved = solvedByDifficulty['EASY'] + solvedByDifficulty['MEDIUM'] + solvedByDifficulty['HARD'];
          const totalProblems = this.problemStats.totalCount;
          
          // 直接计算未开始的题目数量，不再使用"尝试中"的概念
          const notStarted = totalProblems - totalSolved;
          
          this.progressOption.series[0].data = [
            { value: totalSolved, name: '已解决', itemStyle: { color: '#42b983' } },
            { value: notStarted, name: '未开始', itemStyle: { color: '#909399' } }
          ];
          
          // 更新顶部卡片数据
          this.userStats.solvedCount = totalSolved;
          
          // 计算本周新增题目数（这里只是模拟，可以根据实际需求调整）
          const oneWeekAgo = new Date();
          oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
          const oneWeekAgoStr = oneWeekAgo.toISOString().split('T')[0];
          
          let weeklyCount = 0;
          this.activityData.forEach(([date, count]) => {
            if (date >= oneWeekAgoStr) {
              weeklyCount += count;
            }
          });
          
          this.userStats.weeklyIncrease = weeklyCount;
        } else {
          console.error('获取用户难度统计失败：', response.data.message);
        }
      } catch (error) {
        console.error('获取用户难度统计失败:', error);
      }
    },
    // 获取提交记录和计算正确率
    async fetchSubmissions() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          console.error('用户未登录');
          return;
        }

        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getSubmissionByUserId/${userId}`
        });

        if (response.data.result === 'success') {
          this.recentSubmissions = response.data.recentSubmissions;
          
          // 计算正确率
          if (this.recentSubmissions.length > 0) {
            const acceptedCount = this.recentSubmissions.filter(
              submission => submission.status === 'Accepted'
            ).length;
            
            this.userStats.totalSubmissions = this.recentSubmissions.length;
            this.userStats.acceptRate = Math.round((acceptedCount / this.recentSubmissions.length) * 100);
            
            // 模拟上周的正确率变化（在实际应用中，这应该从历史数据中计算）
            this.userStats.acceptRateChange = Math.round(Math.random() * 5); // 随机值，仅用于演示
          }
        } else {
          console.error('获取提交记录失败：', response.data.message);
        }
      } catch (error) {
        console.error('获取提交记录失败:', error);
      }
    }
  },
  async created() {
    // 首先获取题目统计信息
    await this.fetchProblemStats();
    
    // 获取用户活动历史
    await this.fetchUserActivityHistory();
    
    // 获取提交记录
    await this.fetchSubmissions();
    
    // 获取难度统计
    await this.fetchUserDifficultyStats();
  }
}
</script>

<style scoped>
.statistics {
  min-height: 100vh;
  background: #f0f7ff;
}

.main-content {
  margin-left: 60px;
  padding: 20px;
}

/* 统计卡片样式 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  display: flex;
  gap: 16px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  background: #e8f4ff;
  color: #3498db;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-info h3 {
  color: #5b7b9a;
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-value {
  color: #2c3e50;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-trend {
  font-size: 12px;
  color: #5b7b9a;
}

.stat-trend.positive {
  color: #42b983;
}

/* 统计面板网格 */
.stat-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.stat-panel {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

.stat-panel h2 {
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 18px;
}

/* 难度分布样式 */
.difficulty-stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.difficulty-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.difficulty-label {
  width: 80px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #5b7b9a;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.dot.easy { background: #42b983; }
.dot.medium { background: #e6a23c; }
.dot.hard { background: #f56c6c; }
.dot.solved { background: #42b983; }
.dot.attempted { background: #e6a23c; }
.dot.unsolved { background: #909399; }

.difficulty-bar {
  flex: 1;
  height: 8px;
  background: #f0f7ff;
  border-radius: 4px;
  position: relative;
}

.difficulty-bar .progress {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: #3498db;
  border-radius: 4px;
}

.difficulty-bar .value {
  position: absolute;
  right: -50px;
  top: 50%;
  transform: translateY(-50%);
  color: #5b7b9a;
  font-size: 14px;
}

/* 最近提交样式 */
.recent-submissions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.submission-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8faff;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.submission-item:hover {
  transform: translateX(4px);
  background: #f0f7ff;
}

.submission-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.problem-title {
  color: #2c3e50;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.difficulty-tag {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
  font-weight: 500;
}

.difficulty-tag.easy {
  background-color: #42b983;
}

.difficulty-tag.medium {
  background-color: #ffa502;
}

.difficulty-tag.hard {
  background-color: #ff4757;
}

.submission-time {
  color: #5b7b9a;
  font-size: 12px;
}

.submission-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
}

.submission-item.accepted .submission-status {
  color: #42b983;
}

.submission-item.wrong.answer .submission-status {
  color: #ff4757;
}

.submission-item.time.limit.exceeded .submission-status {
  color: #ffa502;
}

.submission-item.runtime.error .submission-status {
  color: #ff6b81;
}

.submission-item.compilation.error .submission-status {
  color: #747d8c;
}

/* 图表占位符样式 */
.calendar-placeholder, .ring-placeholder {
  width: 100%;
  height: 200px;
  background: #f8faff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #5b7b9a;
}

.progress-legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #5b7b9a;
  font-size: 14px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart {
  height: 100%;
  width: 100%;
}
</style> 